package algotithm.leetcode.string.test692;

import java.util.*;

/**
 * @author 25068
 * @Date 2021/5/20 8:30
 * @Title 692. 前K个高频单词
 */
public class Solution {


    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] words = {"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"};
        int k = 4;
        List<String> strings = solution.topKFrequent(words, k);
        System.out.println(strings);
    }

    public List<String> topKFrequent(String[] words, int k) {
        Map<String,Integer> map = new HashMap<>(1024);
        for (String word : words) {
            map.put(word,map.getOrDefault(word,0) + 1);
        }
        List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            if (o1.getValue().equals(o2.getValue())) {
                return o1.getKey().compareTo(o2.getKey());
            } else {
                return o2.getValue() - o1.getValue();
            }
        });
        List<String> res = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            res.add(list.get(i).getKey());
        }
        return res;
    }

}
